 //
//  HttpClient.m
//  MaiJianBaseProject
//
//  Created by Michael Fan on 14-7-9.
//  Copyright (c) 2014年 Michael Fan. All rights reserved.
//

#import "HttpClient.h"
#import "NSString+MD5.h"

@implementation HttpClient
{
    NSString * key_obj;
    
}

+ (instancetype)manager
{
    static dispatch_once_t request;
    static HttpClient *httprequest = nil;
    dispatch_once(&request, ^{
        httprequest = [[HttpClient alloc] initWithBaseURL:[NSURL URLWithString:serverUrl]];
    });
    return httprequest;
}

- (instancetype)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    
#pragma -mark 设置请求超时
    self.requestSerializer.timeoutInterval = kHttpRequestTimeOutInterval;
    self.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"charset=utf-8", @"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFHTTPResponseSerializer serializer];
 
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    return self;
}


-(void)requestHearderSet
{
#pragma -mark 设置http-header
    
    [self.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
}

#pragma -mark 请求错误处理--根据不同error构造包含用户提示内容的error-返回给各页面处理错误提示
-(NSError *)parseRequestErrorDomain:(NSError *)requestError
{
   // DLog(@"request_error===%@==",requestError);
    //do manage error
    NSString* errorString;
    if (requestError.code == NSURLErrorTimedOut)
    {
        errorString = (@"请求数据超时!");
    }
    else if (requestError.code <= 8 && requestError.code>0)
    {
        errorString = [requestError domain];
    }
    else
    {
        errorString = [NSString stringWithFormat:@"网络错误,请求数据失败!"];
    }
   
    return [NSError errorWithDomain:errorString code:requestError.code userInfo:nil];
}

//处理request-success-result
-(void)requestSuccessResult:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                  operation:(AFHTTPRequestOperation *)operation
                   response:(id)responseObject
{
    
    if (![[responseObject class] isSubclassOfClass:[NSDictionary class]])
    {
      responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    }
    
    //DLog(@"请求成功==%@",responseObject);
    
    //请求成功-状态Success
    NSString * str = @"";
    str = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"status"]];
        
    if ([str isEqualToString:@"ok"] || [str isEqualToString:@"1"] || stringIsEmpty(str))//str == 0
    {
        if (success)
            success(operation, responseObject);
    }else
    {
        if (failure)
        {
            if (![responseObject objectForKey:@"errorMsg"])
            {
                 failure(operation, [NSError errorWithDomain:@"网络错误" code:[[responseObject objectForKey:@"error_code"] intValue] userInfo:nil]);
            }else
            {
                 failure(operation, [NSError errorWithDomain:[responseObject objectForKey:@"errorMsg"] code:[[responseObject objectForKey:@"errorCode"] intValue] userInfo:nil]);
            }

        }
    }
}

-(void)requestOtherSuccessResult:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                  operation:(AFHTTPRequestOperation *)operation
                   response:(id)responseObject
{
    //请求成功-状态Success
     if (success)
      success(operation, responseObject);
}


- (AFHTTPRequestOperation *)GET:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [self requestHearderSet];
    
    if (![URLString hasPrefix:@"http"])
    {
        URLString = [NSString stringWithFormat:@"%@%@",requestAPI,URLString];
        URLString = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
    }
    
    /*
    NSTimeInterval time=[[NSDate date] timeIntervalSince1970];// (NSTimeInterval) time = 1427189152.313643
    long long int currentTime=(long long int)time;      //NSTimeInterval返回的是double类型
    NSString *tempTime = [NSString stringWithFormat:@"%lld",currentTime];
     
    if([URLString rangeOfString:@"?"].location == NSNotFound)
     {
    URLString = [NSString stringWithFormat:@"%@?api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
    }
    else
    {
      URLString = [NSString stringWithFormat:@"%@&api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
    }
    NSString * strMd5 = [NSString stringWithFormat:@"%@dbb66bc015db74b4652d51b270a720ca",URLString];

    URLString = [NSString stringWithFormat:@"%@&sign=%@",URLString,[strMd5 MD5]];
    */
    
    if([URLString rangeOfString:@"?"].location == NSNotFound)
    {
        URLString = [NSString stringWithFormat:@"%@?api=2",URLString];
    }
    else
    {
        URLString = [NSString stringWithFormat:@"%@&api=2",URLString];
    }
    
    DLog(@"get==%@",URLString);
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:URLString parameters:nil error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
        success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
            [self requestSuccessResult:success failure:failure operation:operation response:responseObject];
        }
        failure:^(AFHTTPRequestOperation *operation, NSError *error)
        {
            [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
            //失败
            if (failure)
            {
                failure(operation, [self parseRequestErrorDomain:error]);
            }
    }];
    
    [self.operationQueue addOperation:operation];
    
    return operation;
}


//失败block如果为nil-则不给网络错误提示-也可能导致加载烽火轮不消失
- (AFHTTPRequestOperation *)POSTOTHER:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
{
    [parameters setObject:gApp.selfapp_Version forKey:@"appv"];
    [parameters setObject:@"ios" forKey:@"os"];

    [self requestHearderSet];
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];

    if (![URLString hasPrefix:@"http"])
    {
        URLString = [NSString stringWithFormat:@"%@%@",requestAPI,URLString];
        URLString = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
    }
    if([URLString rangeOfString:@"?"].location == NSNotFound)
    {
        URLString = [NSString stringWithFormat:@"%@?api=2",URLString];
    }
    else
    {
        URLString = [NSString stringWithFormat:@"%@&api=2",URLString];
    }
     //DLog(@"POST===URLString-->(%@)===parameters-->(%@)",URLString,parameters);
 
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
         [self requestSuccessResult:success failure:failure operation:operation response:responseObject];
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
         //失败
         if (failure)
         {
             failure(operation, [self parseRequestErrorDomain:error]);
         }
         
     }];
    [self.operationQueue addOperation:operation];
    
    return operation;
}






#pragma mark
- (void)POST:(NSString *)URLString
                      parameters:(id)parameters
                         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    if (![URLString hasPrefix:@"http"])
    {
        URLString = [NSString stringWithFormat:@"%@%@",requestAPI,URLString];
        URLString = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
    }
    
    /*
    NSTimeInterval time=[[NSDate date] timeIntervalSince1970];// (NSTimeInterval) time = 1427189152.313643
    long long int currentTime=(long long int)time;      //NSTimeInterval返回的是double类型
    NSString *tempTime = [NSString stringWithFormat:@"%lld",currentTime];
    
    if([URLString rangeOfString:@"?"].location == NSNotFound)
     {
     URLString = [NSString stringWithFormat:@"%@?api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
     }
     else
     {
     URLString = [NSString stringWithFormat:@"%@&api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
     }
     
    NSString * strMd5 = [NSString stringWithFormat:@"%@dbb66bc015db74b4652d51b270a720ca",URLString];
    
   // URLString = [NSString stringWithFormat:@"%@&sign=%@",URLString,[strMd5 MD5]];
    [parameters setObject:[strMd5 MD5] forKey:@"sign"];
     */
    
    if([URLString rangeOfString:@"?"].location == NSNotFound)
    {
        URLString = [NSString stringWithFormat:@"%@?api=2",URLString];
    }
    else
    {
        URLString = [NSString stringWithFormat:@"%@&api=2",URLString];
    }
    DLog(@"POST===URLString-->(%@)===parameters-->(%@)",URLString,parameters);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer.timeoutInterval = kHttpRequestTimeOutInterval;
   
    NSMutableDictionary *dict = [parameters mutableCopy];
    
    [manager POST:URLString parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
         [self requestSuccessResult:success failure:failure operation:operation response:responseObject];
         
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
         //失败
         if (failure)
         {
             failure(operation, [self parseRequestErrorDomain:error]);
         }
    }];
}


- (AFHTTPRequestOperation* )PUT:(NSString *)URLString
                     parameters:(id)parameters
                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [self requestHearderSet];
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    
    if (![URLString hasPrefix:@"http"])
    {
        URLString = [NSString stringWithFormat:@"%@%@",requestAPI,URLString];
        URLString = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
    }

  
    NSString * strParameters = [self writeWithObject:parameters];
    NSString * changesParam = [strParameters stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    changesParam = [changesParam stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    /*
    NSTimeInterval time=[[NSDate date] timeIntervalSince1970];// (NSTimeInterval) time = 1427189152.313643
    long long int currentTime=(long long int)time;      //NSTimeInterval返回的是double类型
    NSString *tempTime = [NSString stringWithFormat:@"%lld",currentTime];
    
     if([URLString rangeOfString:@"?"].location == NSNotFound)
     {
     URLString = [NSString stringWithFormat:@"%@?api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
     }
     else
     {
     URLString = [NSString stringWithFormat:@"%@&api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
     }
    
    NSString * strMd5 = [NSString stringWithFormat:@"%@dbb66bc015db74b4652d51b270a720ca",URLString];
   // URLString = [NSString stringWithFormat:@"%@&sign=%@",URLString,[strMd5 MD5]];
    [parameters setObject:[strMd5 MD5] forKey:@"sign"];
     */
    
    if([URLString rangeOfString:@"?"].location == NSNotFound)
    {
        URLString = [NSString stringWithFormat:@"%@?api=2",URLString];
    }
    else
    {
        URLString = [NSString stringWithFormat:@"%@&api=2",URLString];
    }
    DLog(@"put==加密后===-->(%@)===parameters-->%@==",URLString,changesParam);
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:URLString parameters:nil error:nil];
    
     request.HTTPBody=[changesParam dataUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
         [self requestSuccessResult:success failure:failure operation:operation response:responseObject];
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
         //失败
         if (failure)
         {
             failure(operation, [self parseRequestErrorDomain:error]);
         }
         
     }];
    [self.operationQueue addOperation:operation];
    
    return operation;
}


- (NSString *)writeWithObject:(id)obj
{
    NSError* error = nil;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:obj
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (error != nil)
    {
        return nil;
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}

- (AFHTTPRequestOperation *)UPLOADIMAGE:(NSString *)URLString
                            uploadImage:(UIImage *)image
                            uploadImageName:(NSString *)imageName
                             parameters:(id)parameters
                                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [self requestHearderSet];
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    
    if (![URLString hasPrefix:@"http"])
    {
        URLString = [NSString stringWithFormat:@"%@%@",requestAPI,URLString];
        URLString = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
    }
  /*
    NSTimeInterval time=[[NSDate date] timeIntervalSince1970];// (NSTimeInterval) time = 1427189152.313643
    long long int currentTime=(long long int)time;      //NSTimeInterval返回的是double类型
    NSString *tempTime = [NSString stringWithFormat:@"%lld",currentTime];
    
   if([URLString rangeOfString:@"?"].location == NSNotFound)
   {
   URLString = [NSString stringWithFormat:@"%@?api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
   }
   else
   {
   URLString = [NSString stringWithFormat:@"%@&api=2&app_id=c99ae561f36db004&timestamp=%@",URLString,tempTime];
   }
    NSString * strMd5 = [NSString stringWithFormat:@"%@dbb66bc015db74b4652d51b270a720ca",URLString];
   // URLString = [NSString stringWithFormat:@"%@&sign=%@",URLString,[strMd5 MD5]];
    [parameters setObject:[strMd5 MD5] forKey:@"sign"];
    */
    
    if([URLString rangeOfString:@"?"].location == NSNotFound)
    {
        URLString = [NSString stringWithFormat:@"%@?api=2",URLString];
    }
    else
    {
        URLString = [NSString stringWithFormat:@"%@&api=2",URLString];
    }
    DLog(@"UPLOADIMAGE===加密后-->(%@)===parameters-->(%@)",URLString,parameters);
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:URLString
                                                parameters:parameters
                                                constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                                {
                                                        NSData *imageData = UIImageJPEGRepresentation(image, 1);
                                                    [formData appendPartWithFileData:imageData name:imageName fileName:@"head.jpg" mimeType:@"image/jpeg"];//
                                                    
                                                }
                                                                                    error:nil];
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
                            success:^(AFHTTPRequestOperation *operation, id responseObject)
                            {
                                [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
                                [self requestSuccessResult:success failure:failure operation:operation response:responseObject];
                            }
                            failure:^(AFHTTPRequestOperation *operation, NSError *error)
                            {
                                [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
                                    if (failure)
                                    {
                                        failure(operation, [self parseRequestErrorDomain:error]);
                                    }
                            }];
    // 启动上传
    [self.operationQueue addOperation:operation];
    return operation;

    
}



- (void)UPLOADIMAGEQINIU:(NSString *)URLString
                            uploadImage:(UIImage *)image
                        uploadImageName:(NSString *)imageName
                             parameters:(id)parameters
                                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    
    if (![URLString hasPrefix:@"http"])
    {
        URLString = [NSString stringWithFormat:@"%@%@",requestAPI,URLString];
        URLString = [[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString];
    }

    [self requestHearderSet];
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:URLString parameters:nil error:nil];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
                                           success:^(AFHTTPRequestOperation *operation, id responseObject)
                                           {
                                             [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
                                             if (![[responseObject class] isSubclassOfClass:[NSDictionary class]])
                                             {
                                                   responseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                            }
                    
                                            NSMutableDictionary * dicResults = [responseObject objectForKey:requestDataKey];
                                             NSString * qiniutoken = NullObjToString([dicResults objectForKey:@"uploadToken"]);
                                             
                                             QNUploadManager *upManager = [[QNUploadManager alloc] init];//上传
                                             
                                             NSData *imageData = UIImageJPEGRepresentation(image, 1);
                                             [upManager putData:imageData
                                                            key:imageName
                                                          token:qiniutoken
                                                       complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp)
                                              {
                                                 // DLog(@"info:%@===resp:%@", info,resp);
                                                  if ([info statusCode] == 200)//上传成功
                                                  {
                                                      [dicResults setObject:imageName forKey:@"reomteKey"];
                                                      [responseObject removeObjectForKey:requestDataKey];
                                                      [responseObject setObject:dicResults forKey:requestDataKey];
                                                      
                                                      [self requestSuccessResult:success failure:failure operation:operation response:responseObject];
                                                  } else
                                                  {
                                                      NSError * error;
                                                        failure(operation,[self parseRequestErrorDomain:error]);
                                                  }
                                              }option:nil];
                                         }
                                        failure:^(AFHTTPRequestOperation *operation, NSError *error)
                                         {
                                             [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
                                             //失败
                                             if (failure)
                                             {
                                                 failure(operation, [self parseRequestErrorDomain:error]);
                                             }
                                         }];
    
    [self.operationQueue addOperation:operation];

    
}



@end








